package com.github.binarylei.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: leigang
 * @version: 2018-04-06
 */
public class ZkCuratorBase {

    private static final String CONNECT_ADDR = "127.0.0.1:2181";
    private static final int SEESION_OUTTIME = 5 * 1000;
    
    @Test
    public void test() throws Exception {
        //1. 重试策略：初试时间为1s，重试10次
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 10);

        //2. 通过工厂创建连接，可指定名称空间 curator
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_ADDR)
                .sessionTimeoutMs(SEESION_OUTTIME)
                .retryPolicy(retryPolicy)
                .namespace("curator")
                .build();

        //3. 开启连接
        cf.start();

        //4. 创建，支持递归创建 /curator/test
        cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .forPath("/test", "curator".getBytes());

        //5. 获取
        Stat stat = new Stat();
        byte[] data = cf.getData().storingStatIn(stat).forPath("/test");
        System.out.println("/test：" + new String(data));

        //6. 修改
        cf.setData().withVersion(stat.getVersion()).forPath("/test", "curator-xxx".getBytes());

        //7. 递归删除
        cf.delete().guaranteed().deletingChildrenIfNeeded().forPath("/test");

        //8. 回调函数
        ExecutorService pool = Executors.newCachedThreadPool();
        cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework cf, CuratorEvent event) throws Exception {
                        System.out.println("code：" + event.getResultCode());
                        System.out.println("type：" + event.getType());
                        System.out.println("线程为：" + Thread.currentThread().getName());
                    }
                }, pool)
                .forPath("/test", "curator-test".getBytes());

        System.out.println("主线程为：" + Thread.currentThread().getName());

        Thread.sleep(100 * 1000);
        cf.close();
    }
}
